﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using VentaElectrodomesticos.Sql;
using System.Data.SqlClient;
using System.Security.Cryptography;

namespace VentaElectrodomesticos.AbmUsuario
{
    public partial class FormEditarUsuario : Form
    {
        private ClaseSQL sql;
        private String id;
        private String contraseña;

        public FormEditarUsuario(String id,
                                String estado,
                                String usuario,
                                String password)
        {
            InitializeComponent();
            this.id = id;
            this.textBoxUsuario.Text = usuario;
            this.contraseña = password;
            sql = new ClaseSQL();
            Usuario oUsuario = new Usuario();
            oUsuario.completarRoles(this.dataGridView1);
            this.llenarRolesActivos();
            if (estado.Equals("1"))
            {
                btnHabilitar.Visible = false;
            }

        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                sql.Open();
                String[,] parametros = new String[2, 3];
                String sp = "LAG.sp_modificarUsuario";
                parametros[0, 0] = "@id";
                parametros[0, 1] = "@password";
                parametros[0, 2] = "@roles";
                
                parametros[1, 0] = this.id;
                if (this.textBoxPassword.Text != "")
                    parametros[1, 1] = this.encriptarPassword(this.textBoxPassword.Text);
                if (this.dataGridView1.Rows.Count > 0)
                {
                    for (int i = 0; i < this.dataGridView1.Rows.Count; i++)
                    {
                        if (((this.dataGridView1.Rows[i].Cells[2]).Value) != null && (this.dataGridView1.Rows[i].Cells[2].Value.ToString() == "1"))
                        {
                            if (parametros[1, 2] == null)
                                parametros[1, 2] = "¦" + (String)this.dataGridView1[0, i].Value;
                            else
                                parametros[1, 2] += "¦" + (String)this.dataGridView1[0, i].Value;
                        }
                    }
                }
                //validación de datos
                Boolean bol = true;
                
                if (parametros[1,1] != null){ //contraseña
                        if (this.textBoxPassword.Text != this.textBoxConfirmaPassword.Text)
                        { 
                            bol = false;
                            MessageBox.Show("La contraseña ingresada es incorrecta", "Error");
                        }
                }
                else{
                    parametros[1, 1] = this.contraseña;
                }
                if (parametros[1, 2] == null){ //roles
                    bol = false;
                    MessageBox.Show("No se ha seleccionado ningún rol", "Error");
                }
                
                if (bol){
                    //se hace el insert de los datos 
                    SqlDataReader reader = sql.ejecutarStoredProcedure(sp, parametros);
                    if (reader != null)
                    {
                        MessageBox.Show("Se han modificado los datos del Empleado.", "Success!");
                        this.Close();
                    }
                }
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.Message + "\n" + ex.StackTrace, "Error!");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n" + ex.StackTrace, "Error app");
            }
            finally
            {
                sql.Close();
            }
        }

        private string encriptarPassword(string CadenaOriginal)
        {
            System.Security.Cryptography.HashAlgorithm hashValue = new
           System.Security.Cryptography.SHA256CryptoServiceProvider();

            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(CadenaOriginal);

            byte[] byteHash = hashValue.ComputeHash(bytes);

            hashValue.Clear();

            return (Convert.ToBase64String(byteHash));
            //return byteHash;
        }

        private void llenarRolesActivos() {
            try
            {
                sql.Open();

                String defaultquery = "SELECT idRol FROM LAG.usuarios_roles WHERE idUsuario = " + (String)this.id;
                SqlDataReader reader = sql.busquedaSQLDataReader(defaultquery);
                while (reader.Read())
                {
                    if (this.dataGridView1.Rows.Count > 0)
                    {
                        for (int i = 0; i < this.dataGridView1.Rows.Count ; i++)
                        {
                            if (((this.dataGridView1.Rows[i].Cells[0]).Value) != null && (this.dataGridView1.Rows[i].Cells[0].Value.ToString() == reader[0].ToString()))
                            {
                                this.dataGridView1.Rows[i].Cells[2].Value = "1";
                            }
                        }
                    }
                }
                reader.Close();
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.Message, "Error!");
            }
            finally
            {
                sql.Close();
            }
        }

        private void buttonCancelar_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnHabilitar_Click(object sender, EventArgs e)
        {
            bool habilitado = sql.habilitarRegistro("LAG.usuarios", "idUsuario", this.id);

            if (habilitado)
            {
                btnHabilitar.Visible = false;
            }
        }

        
    }
}
